const {buildSchema } = require('graphql')
const express = require('express')
const { graphqlHTTP } = require('express-graphql')
const {v4:uuidv4} = require('uuid')
const cors = require('cors')

const students = [
    { id: '1', name: 'xm', age: 13, hobbies: ['画画', '读书'] },
    { id: '2', name: 'cxk', age: 15, hobbies: ['唱', '跳', 'rap'] }
]

const schema = buildSchema(`
    type Student{
        id:ID!
        name:String!
        age:Int!
        hobbies:[String!]!
    }
    type Query {
        students:[Student]
        student(id:ID!):Student
    }
    input InputStu{
        name:String!
        age:Int!
        hobbies:[String!]
    }
    input UpdateStuInput{
        name:String!
        age:Int!
    }
    type DeletionStatus{
        success: Boolean
    }
    type Mutation {
        create(inputStu:InputStu):Student!
        update(id:ID!,stu:UpdateStuInput):Student
        del(id:ID!):DeletionStatus
    }
`)
const root = {
    // 查询所有
    students(){
        return students
    },
    // 查询单个
    student({id}){
        return students.find(item=>item.id === id)
    },
    // 新增
    create({inputStu}){
       inputStu.id = uuidv4()
       students.push(inputStu)
       return inputStu
    },
    // 修改
    update({id,stu}){
        const student = students.find(student => student.id === id)
        if(student){
            student.name = stu.name
            student.age = stu.age
        }
        return student
    },
    // 删除
    del({id}){
        const idnex = students.findIndex(student => student.id === id)
        students.splice(idnex,1)
        return {
            success:true
        }
    }
}

const app = express()
app.use(cors())
app.use('/graphql', graphqlHTTP({
    schema,
    rootValue: root,
    graphiql: true
}))
app.listen(3000)
